﻿using Abp.Authorization;
using Abp.Linq.Expressions;
using Abp.UI;
using Basefr.App;
using Microsoft.AspNetCore.Mvc;
using Paas.App.Interface.Meta.Dtos;
using Paas.App.Interface.Meta.Messages;
using Paas.App.Interface.Meta;
using Paas.App.Interface.MetaTables;
using Paas.App.Interface.MetaTables.Dtos;
using Paas.App.Interface.MetaTables.Messages;
using Paas.Core;
using Paas.Core.Const.Enums;
using Paas.Core.Meta.Entities;
using Paas.Core.MetaTables.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Paas.App.Interface.MetaTableFields;
using Abp.Domain.Entities;
using Abp.Domain.Repositories;
using MySqlX.XDevAPI.Common;

namespace Paas.App.MetaTables
{
    [Route("metaTables-metaTableField")]

    [AbpAuthorize()]
    public class MetaTableFieldAppService : AppService, IMetaTableFieldAppService
    {
        private readonly IMainRepository<MetaTableField, Guid> _metaTableFieldRepo;
        private readonly IMainRepository<MetaField, Guid> _metaFieldRepo;


        public MetaTableFieldAppService(IMainRepository<MetaTableField, Guid> metaTableFieldRepo, IMainRepository<MetaField, Guid> metaFieldRepo)
        {
            _metaTableFieldRepo = metaTableFieldRepo;
            _metaFieldRepo = metaFieldRepo;
        }

        [HttpPost(nameof(SaveMetaTableField))]
        public async Task<SaveMetaTableFieldOutput> SaveMetaTableField(SaveMetaTableFieldInput input)
        {
            if (input == null) throw new UserFriendlyException("保存失败：input为空！");

            #region 更新
            if (input.Item?.Id != null && input.Item?.Id != Guid.Empty)
            {
                //var entity = ObjectMapper.Map<MetaTableField>(input.Item);
                var uData = await _metaTableFieldRepo.GetAsync(input.Item.Id);
                if (uData == null) throw new UserFriendlyException("未找到需要更新的对象！");

                //需要更新的字段
                uData.ReLabel = input.Item.ReLabel;
                uData.SortNum= input.Item.SortNum;

                await _metaTableFieldRepo.UpdateAsync(uData);
                return new SaveMetaTableFieldOutput();
            }
            #endregion

            //设置一些默认的值

            #region 新增
            ////判断是否有数据
            if (input.TableFields?.Count>0)
            {
                //表格字段全部删除，重新增加
                //    await _metaTableFieldRepo.HardDeleteAsync(p => p.MetaTableId==input.MetaTableId);//硬删除

                //查询表格字段同一formid的最大SortNum值,没有则=0
                var maxSortNum = _metaTableFieldRepo.GetAllList(p => p.MetaTableId== input.MetaTableId)?.MaxBy(p => p.SortNum)?.SortNum??0;
                foreach (var item in input.TableFields)
                {
                    var metaField = _metaFieldRepo.FirstOrDefault(p => p.Id.ToString()==item);
                    if (metaField != null)
                    {
                        maxSortNum++;
                        var entity = new MetaTableField()
                        {
                            MetaTableId=input.MetaTableId,
                            MetaFieldId=metaField.Id,
                            //新增时默认与原字段名称相同
                            ReLabel=metaField.Label,
                            //顺序编号
                            SortNum=maxSortNum
                        };
                        await _metaTableFieldRepo.InsertAsync(entity);
                    }
                }
            }
            #endregion
            return new SaveMetaTableFieldOutput();
        }

        [HttpPost(nameof(SearchMetaTableField))]
        public async Task<SearchMetaTableFieldOutput> SearchMetaTableField(SearchMetaTableFieldInput input)
        {
            Expression<Func<MetaTableField, bool>> predicate = p => true;
            if (!string.IsNullOrWhiteSpace(input.ReLabel))
            {
                predicate = predicate.And(p => p.ReLabel.Contains(input.ReLabel.Trim()));
            }
            if (input.MetaTableId!=null&&input.MetaTableId!=Guid.Empty)
            {
                predicate = predicate.And(p => p.MetaTableId == input.MetaTableId);
            }

            var result = _metaTableFieldRepo.GetAllIncluding(p=>p.MetaField).Where(predicate);
            var res = result.OrderBy(p => p.SortNum).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();

            var totalCount = result.Count();
            var resultItems = ObjectMapper.Map<List<MetaTableFieldDto>>(res);
            //foreach (var item in resultItems)
            //{
            //    //获取字段信息
            //    var metaFiled = _metaFieldRepo.FirstOrDefault(p => p.Id.ToString()==item.MetaFieldId);
            //    if (metaFiled != null)
            //    {
            //        item.MetaField=ObjectMapper.Map<MetaFieldDto>(metaFiled);
            //    }
            //}
            return new SearchMetaTableFieldOutput { Items = resultItems, TotalCount = totalCount };
        }

        [HttpPost(nameof(DeleteMetaTableField))]
        public async Task<DeleteMetaTableFieldOutput> DeleteMetaTableField(DeleteMetaTableFieldInput input)
        {
            //await _metaTableFieldRepo.DeleteAsync(input.Id);
            //硬删除
            var entity = _metaTableFieldRepo.FirstOrDefault(input.Id);
            await _metaTableFieldRepo.HardDeleteAsync(entity);
            return new DeleteMetaTableFieldOutput();
        }

        /// <summary>
        /// 表格添加字段用：筛选表格可用字段
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost(nameof(SearchMetaFieldForTableField))]
        public async Task<SearchMetaFieldForTableFieldOutput> SearchMetaFieldForTableField(SearchMetaFieldForTableFieldInput input)
        {
            //获取相关对象所有已发布字段
            Expression<Func<MetaField, bool>> predicate = p => true;
            if (!string.IsNullOrWhiteSpace(input.ObjectId))
            {
                predicate = predicate.And(p => p.ObjectId == input.ObjectId);
                predicate = predicate.And(p => p.CurrentStatus == MetaStatus.Released);//已发布字段
            }

            var fields = await _metaFieldRepo.GetAllListAsync(predicate);
            //获取表格内已有字段
            var formFields = await _metaTableFieldRepo.GetAllListAsync(p => p.MetaTableId==input.MetaTableId);
            //获得表格还没有的字段
            var result = fields.Where(p => !formFields.Any(q => q.MetaFieldId==p.Id));
            var res = result.OrderByDescending(p => p.SortNum).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            var totalCount = result.Count();
            var resultItems = ObjectMapper.Map<List<MetaFieldDto>>(res);
            return new SearchMetaFieldForTableFieldOutput { Items = resultItems, TotalCount = totalCount };
        }

    }
}
